
var loadingDom = {
    loadPerV: 0,
    maxItemCount: 606,
    createAbsoluteDom(domName, style) {
        style = style || {};
        Object.assign(style, {
            position: "absolute",
        });
        var dom = document.createElement(domName);
        Object.assign(dom.style, style);
        return dom;
    },
    addPic(src, x, y) {
        var img = new Image();
        img.src = src;
        Object.assign(img.style, {
            position: "absolute",
            pointerEvents: "none",
        });
        this.splash.appendChild(img);
        let cm = new CMelement(img, x, y, 0, 0);
        this.twidget.addMe(cm);
        img.onload= function(){
            cm.width = img.naturalWidth;
            cm.height = img.naturalHeight;
        };
        return cm;
    },
    init: function () {
        this.twidget = new TWidget();
        this.splash = document.getElementById("splash");

        let loadingConfig = window.gameConfig.loading || {
            inGame: "BoxLoading",
            bgUrl: "",
            bgInAsset: "",
            hasLabel: true,
            hasIcon: true,
        };

        //背景
        let bgUrl = "bg.jpg";
        if (loadingConfig.bgUrl) {
            bgUrl = `${window["GamePath"]}/${loadingConfig.bgUrl}`
        }
        this.addPic(bgUrl, 0, 0);

        //黑色
        var black = this.createAbsoluteDom("div", {
            left: "0",
            top: "0",
            width: "100%",
            height: "100%",
            background: "rgba(0,0,0,0.7)",
        });
        this.splash.appendChild(black);

        //文字
        if (loadingConfig.hasLabel) {
            this.loadWord = this.createAbsoluteDom("div", {
                position: "absolute",
                color: "white",
            });
            this.splash.appendChild(this.loadWord);
            this.loadWord.innerHTML = `<span>0</span>%`;
            this.twidget.addMe(new CMelement(this.loadWord, 0, 0, 750));
            this.twidget.addMe(new FontMelement(this.loadWord, 45));
            this.loadWordValue = this.loadWord.children[0];
        }

        //图标
        if (loadingConfig.hasIcon) {
            this.picMe = this.addPic("pad.png", 0, -120, 150, 132);
            Object.assign(this.picMe.dom.style, {
                transition: "top .8s ease-in-out"
            });
            this._picMeLoopId = setInterval(function () {
                this.picMe.y = this.picMe.y == -120 ? -100 : -120;
            }.bind(loadingDom), 800);
        }

        this._updateId = setInterval(this.update.bind(this), 16);
    },
    update() {
        this.twidget.update();
        if (this.loadWordValue) {
            this.loadWordValue.innerText = this.loadPerV.toFixed(0);
        }
    },
    finish() {
        if (!this.__syncLoadingOk) {
            return;
        }
        this.update();
        if (this._updateId) {
            clearInterval(this._updateId);
        }
        if (this._picMeLoopId) {
            clearInterval(this._picMeLoopId);
        }
    },
    fadeOut(){
        var opacity = 1;
        var intervalId = setInterval(function () {
            opacity -= 0.08;
            splash.style.opacity = opacity.toFixed(2);
            if (opacity <= 0) {
                clearInterval(intervalId);
                splash.style.display = 'none';
                window.utils.msgHub.emit(window.utils.macro.EVENTS.SPLASH_OUT);
            }
        }, 50);
    }
};


window.boot = function () {
    var settings = window._CCSettings;
    window._CCSettings = undefined;
    var onProgress = null;

    var RESOURCES = cc.AssetManager.BuiltinBundleName.RESOURCES;
    var INTERNAL = cc.AssetManager.BuiltinBundleName.INTERNAL;
    var MAIN = cc.AssetManager.BuiltinBundleName.MAIN;
    function setLoadingDisplay() {
        // Loading splash scene
        var splash = document.getElementById('splash');
        onProgress = function (finish, total) {
            var percent = 100 * finish / total;
            loadingDom.loadPerV = percent;
        };
        splash.style.display = 'block';
        cc.director.once(cc.Director.EVENT_AFTER_SCENE_LAUNCH, function () {
            console.log("after launch");
            loadingDom.__syncLoadingOk = true;
            loadingDom.finish();
        });
    }

    var onStart = function () {

        cc.view.enableRetina(true);
        cc.view.resizeWithBrowserSize(true);

        if (cc.sys.isBrowser) {
            setLoadingDisplay();
        }

        if (cc.sys.isMobile) {
            if (settings.orientation === 'landscape') {
                cc.view.setOrientation(cc.macro.ORIENTATION_LANDSCAPE);
            }
            else if (settings.orientation === 'portrait') {
                cc.view.setOrientation(cc.macro.ORIENTATION_PORTRAIT);
            }
            cc.view.enableAutoFullScreen([
                cc.sys.BROWSER_TYPE_BAIDU,
                cc.sys.BROWSER_TYPE_BAIDU_APP,
                cc.sys.BROWSER_TYPE_WECHAT,
                cc.sys.BROWSER_TYPE_MOBILE_QQ,
                cc.sys.BROWSER_TYPE_MIUI,
                cc.sys.BROWSER_TYPE_HUAWEI,
                cc.sys.BROWSER_TYPE_UC,
            ].indexOf(cc.sys.browserType) < 0);
        }

        // Limit downloading max concurrent task to 2,
        // more tasks simultaneously may cause performance draw back on some android system / browsers.
        // You can adjust the number based on your own test result, you have to set it before any loading process to take effect.
        if (cc.sys.isBrowser && cc.sys.os === cc.sys.OS_ANDROID) {
            cc.assetManager.downloader.maxConcurrency = 2;
            cc.assetManager.downloader.maxRequestsPerFrame = 2;
        }

        var launchScene = settings.launchScene;
        var bundle = cc.assetManager.bundles.find(function (b) {
            return b.getSceneInfo(launchScene);
        });

        bundle.loadScene(launchScene, null, onProgress,
            function (err, scene) {
                if (!err) {
                    cc.director.runSceneImmediate(scene);
                    if (cc.sys.isBrowser) {
                        // show canvas
                        var canvas = document.getElementById('GameCanvas');
                        canvas.style.visibility = '';
                        var div = document.getElementById('GameDiv');
                        if (div) {
                            div.style.backgroundImage = '';
                        }
                        // console.log('Success to load scene: ' + launchScene);
                    }
                }
            }
        );

    };
    //canvas透明。
    // cc.macro.ENABLE_TRANSPARENT_CANVAS = true;

    var option = {
        id: 'GameCanvas',
        debugMode: settings.debug ? cc.debug.DebugMode.INFO : cc.debug.DebugMode.ERROR,
        showFPS: settings.debug,
        frameRate: 60,
        groupList: settings.groupList,
        collisionMatrix: settings.collisionMatrix,
    };

    cc.assetManager.init({
        bundleVers: settings.bundleVers,
        remoteBundles: settings.remoteBundles,
        server: settings.server
    });

    var bundleRoot = [INTERNAL];
    settings.hasResourcesBundle && bundleRoot.push(RESOURCES);

    var count = 0;
    function cb(err) {
        if (err) return console.error(err.message, err.stack);
        count++;
        if (count === bundleRoot.length + 1) {
            cc.assetManager.loadBundle(MAIN, function (err) {
                if (!err) cc.game.run(option, onStart);
            });
        }
    }

    cc.assetManager.loadScript(settings.jsList.map(function (x) { return 'src/' + x; }), cb);

    for (var i = 0; i < bundleRoot.length; i++) {
        cc.assetManager.loadBundle(bundleRoot[i], cb);
    }
};

if (window.jsb) {
    var isRuntime = (typeof loadRuntime === 'function');
    if (isRuntime) {
        require('src/settings.js');
        require('src/cocos2d-runtime.js');
        if (CC_PHYSICS_BUILTIN || CC_PHYSICS_CANNON) {
            require('src/physics.js');
        }
        require('jsb-adapter/engine/index.js');
    }
    else {
        require('src/settings.js');
        require('src/cocos2d-jsb.js');
        if (CC_PHYSICS_BUILTIN || CC_PHYSICS_CANNON) {
            require('src/physics.js');
        }
        require('jsb-adapter/jsb-engine.js');
    }

    cc.macro.CLEANUP_IMAGE_CACHE = true;
    window.boot();
}